<script setup>
import IndexHeader from "@/components/IndexHeader.vue";
import { ref,onMounted,watch } from "vue";
import { useRouter, useRoute } from 'vue-router';
import VideoCard from "@/views/index/components/VideoCard.vue";
import VideoApi from "@/apis/VideoApi.js";

const router = useRouter();
const route = useRoute();

// 新增搜索相关的响应式变量
const searchKeyword = ref(route.query.keyword || '')
const isSearchFocused = ref(false)
const searchHistory = ref(['CSGO2', 'React', 'Vue.js', '原神', '搞笑视频'])

// 处理搜索提交
function handleSearch() {
  if (!searchKeyword.value.trim()) return

  // 添加到搜索历史
  if (!searchHistory.value.includes(searchKeyword.value)) {
    searchHistory.value.unshift(searchKeyword.value)
    if (searchHistory.value.length > 6) {
      searchHistory.value.pop()
    }
  }

  // TODO: 实际搜索逻辑
  console.log('搜索关键词:', searchKeyword.value)
  // const res = await VideoApi.videoSearch(searchKeyword.value)
  // console.log('搜索结果',res)
  // result.value = res.data.videos
  router.push({
    path: '/search',
    query: { keyword: searchKeyword.value }, // 更新路由参数
  });
}

// 根据关键字搜索
async function fetchSearchResults(keyword) {
  if (!keyword) return;
  try {
    const res = await VideoApi.videoSearch(keyword);
    result.value = res.data.videos;
  } catch (err) {
    console.error('搜索失败');
  }
}

// 监听路由参数变化
watch(
    () => route.query.keyword,
    (newKeyword) => {
      searchKeyword.value = newKeyword || '';
      fetchSearchResults(newKeyword);
    },
    { immediate: true }
);

// 初始化时执行搜索
onMounted(() => {
  if (searchKeyword.value) {
    fetchSearchResults(searchKeyword.value);
  }
});


// 清除搜索历史
function clearHistory() {
  searchHistory.value = []
}

// 点击历史记录
function searchHistoryItem(keyword) {
  searchKeyword.value = keyword
  handleSearch()
}

// 删除单个历史记录
function removeHistoryItem(index) {
  searchHistory.value.splice(index, 1)
}

const result = ref(null);



</script>


<template>
<div class="header">
  <IndexHeader :scrollTrans="false" :searchType="false"></IndexHeader>
</div>
<div class="centerSearch">
  <div class="search-wrapper">
    <div class="search-container" :class="{ 'is-focused': isSearchFocused }">
      <div class="search-box">
        <el-input
            v-model="searchKeyword"
            placeholder="搜索视频、番剧、用户"
            @focus="isSearchFocused = true"
            @blur="isSearchFocused = false"
            @keyup.enter="handleSearch"
        >
        </el-input>
        <div class="search-btn" @click="handleSearch">
          <i class="iconfont icon-sousuo"></i>
        </div>
      </div>

      <!-- 搜索历史下拉框 -->
      <div v-show="isSearchFocused" class="search-dropdown">
        <div class="search-history">
          <div class="history-header">
            <span>搜索历史</span>
            <span class="clear-history" @click="clearHistory">清空</span>
          </div>
          <div class="history-list">
            <div
                v-for="(item, index) in searchHistory"
                :key="index"
                class="history-item"
            >
              <div class="history-item-content" @click="searchHistoryItem(item)">
                <i class="iconfont icon-time"></i>
                <span>{{ item }}</span>
              </div>
              <i
                  class="iconfont icon-close delete-btn"
                  @click.stop="removeHistoryItem(index)"
              ></i>
            </div>
          </div>
        </div>
      </div>
    </div>
  </div>
</div>
<div class="video_area">
  <VideoCard v-for="(video, index) in result?result:null" :key="index" :video="video" />
</div>
</template>

<style scoped lang="less">
.header {
  width: 100%;
  height: 100px;
  display: flex;
  position: relative;
  flex-direction: column;
  justify-content: flex-start;
  align-items: center;
  left: 0;
  right: 0;
  top: 0;
  bottom: 0;
  z-index: 99;
}

.centerSearch{
  position: relative;
  left: 40%;
  //bottom: 100px;
  flex: 1;
  margin: 0 20px;
  width: 20%;

  .search-wrapper {
    background-color: var(--search-background, rgba(255, 255, 255, 0.8));
    border-radius: 8px;
    padding: 4px;
    transition: all 0.3s;

    .search-container {
      position: relative;

      &.is-focused {
        .search-box {
          border-radius: 4px 4px 0 0;

          .el-input__wrapper {
            border-radius: 4px 4px 0 0;
          }

          .search-btn {
            border-radius: 0 4px 0 0;
          }
        }

        .search-dropdown {
          visibility: visible;
          opacity: 1;
        }
      }
    }

    .search-box {
      display: flex;
      align-items: center;
      height: 32px;
      background-color: #f1f2f3;
      border-radius: 4px;
      transition: all 0.3s;

      :deep(.el-input) {
        width: 100%;

        .el-input__wrapper {
          background: transparent;
          box-shadow: none !important;
          padding-right: 40px;
          border-radius: 4px;
          height: 32px;
        }

        .el-input__inner {
          height: 32px;
          color: #18191c;
          font-size: 14px;

          &::placeholder {
            color: #9499a0;
          }
        }

        .el-input__prefix {
          .iconfont {
            font-size: 16px;
            color: #9499a0;
          }
        }
      }

      .search-btn {
        position: absolute;
        right: 0;
        width: 40px;
        height: 32px;
        display: flex;
        align-items: center;
        justify-content: center;
        cursor: pointer;
        border-radius: 0 4px 4px 0;
        transition: all 0.3s;
        user-select: none;

        &:hover {
          background: var(--search-button-hover, #00aeec);
          .iconfont {
            color: #fff;
          }
        }

        .iconfont {
          font-size: 16px;
          color: #9499a0;
          transition: color 0.3s;
        }
      }
    }

    .search-dropdown {
      position: absolute;
      top: 100%;
      left: -4px;  // 对齐外层padding
      right: -4px; // 对齐外层padding
      background: #fff;
      border-radius: 0 0 8px 8px;
      visibility: hidden;
      opacity: 0;
      transition: all 0.2s;
      z-index: 1000;
      margin-top: -1px; // 消除边框间隙
      box-shadow: 0 0 0 1px #e7e7e7;
    }
  }
}
.video_area {
  position: relative;
  margin-left: 10%;
  margin-right: calc(10% - 30px);
  top: 100px;
  display: grid;
  grid-template-columns: repeat(5, 1fr);
  gap: 20px;
  flex-wrap: wrap;
  margin-bottom: 30px;
  box-shadow: 0 1px 0 0 #e7e7e7;
}
</style>